<!DOCTYPE html>
<html lang="zh">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>css实现导航栏下划线向两边展开效果</title>
    <style>
        ul {
            list-style: none;
            margin: 50px auto;
            width: 500px;
            display: flex;
            position: relative;
        }
        a{
            text-decoration: none;
            color: #000;
        }

        ul>li {
            height: 33px;
            line-height: 33px;
            text-align: center;
            width: auto;
            font-size: 14px;
            margin-right: 30px;
            /* 设置relative,作为伪类::after定位的参照和width的参照基准 */
            position: relative;
            padding: 0 5px;
            cursor: pointer;
        }

        ul>li::before,
        ul>li::after {
            content: '';
            /* 将开始的宽度设置为0,这样才会展示出过渡效果 */
            width: 0;
            height: 2px;
            background-color: pink;
            /* 设置原本定位 */
            position: absolute;
            top: 99%;
            left: 50%;
        }

        ul>li:hover::before {
            /* 实现向左展开效果 */
            /* 鼠标移入改变宽度 */
            width: 100%;
            /* 鼠标移入改变定位位置 */
            left: 2px;
             /* 设置过渡效果 */
            transition: all .5s;
        }
        /* 同上 */
        ul>li:hover::after {
            width: 50%;
            right: 0px;
             /* 设置过渡效果 */
            transition: all .5s;
        }

        .active{
            color: skyblue;
        }
        .active::after,.active::before{
            content: '';
            width: 100%;
            height: 2px;
            background-color: skyblue;
            position: absolute;
            top: 99%;
            left: 0;
        }
        .pseudo::before{
            content: '主菜单';
            width: 45px;
            height: 18px;
            background: rgba(0,0,0,0.4);
            border-radius: 0px 8px 0px 8px;
            position: absolute;
            left: -43px;
            top: -4px;
            margin: 0;
            font-size: 10px;
            text-align: center;
            line-height: 18px;
            color: #fff;
            opacity: .8;
        }
    </style>
</head>

<body>
    <ul>
        <li><a>智慧城</a></li>
        <li><a>苹果商城</a></li>
        <li><a>益田假日里</a></li>
        <li><a>智慧屏</a></li>
        <li><a>穿戴</a></li>
    </ul>
</body>

<script>
    let li = document.querySelectorAll('li');
    let a = document.querySelectorAll('a');
    li[0].className = 'active'
    a[0].className = 'pseudo'
    li.forEach((el,index)=>{
        el.addEventListener('click',function(){
            li.forEach(el=>{
                el.className = '';
            })
            a.forEach(el=>{
                el.className = '';
            })
            a[index].className = 'pseudo'
            el.className = 'active'
        })
    })
</script>
</html>
